<template>
  <div class="advert app-container">
    <el-container>
      <el-aside width="200px" class="pd0">
        <h1 class="f18 pt24 pl20 mb20">页面名称</h1>

        <SelectList ref="selectRef" :list="pageList" :default="defaultPageId" @change="changePage"></SelectList>
        <!-- <el-button @click="refresh2">刷新</el-button> -->
      </el-aside>
      <el-main style="min-height: calc(100vh - 125px)">
        <p>
          <el-button type="primary" @click="addBanner" :disabled="currLenObj.num >= currLenObj.total"> 添加海报 </el-button>
        </p>
        <div class="swiper-time mt16 mb16">
          <el-form :model="form" label-width="auto" style="max-width: 600px">
            <el-form-item label="轮播时间">
              <el-radio-group v-model="form.time" @change="changeSwiperTime">
                <el-radio :label="1" :value="1">每隔五秒切换</el-radio>
                <el-radio :label="2" :value="2">每个十秒切换</el-radio>
                <el-radio :label="3" :value="3">不轮播（手动切换）</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <el-button type="primary">预览</el-button>
        </div>

        <el-table :data="tableData" :show-header="false" style="width: 100%; padding-bottom: 20px">
          <el-table-column prop="img" label="图片" width="220">
            <template #default="scope">
              <!-- 只读状态 -->
              <img v-if="!scope.row.isEdit" :src="scope.row.img" class="td-img" />
              <!-- 编辑状态 -->
              <el-upload
                v-else
                class="avatar-uploader"
                list-type="picture-card"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="
                  (file, fileList) => {
                    handleAvatarChangeIcon(scope.row, file, fileList);
                  }
                "
              >
                <div class="upload-wrap ml26">
                  <img :src="scope.row.img" class="td-img" />
                  <p class="f12">
                    <el-icon style="color: white; margin-right: 5px" class="f16"><RefreshRight /></el-icon>重新上传
                  </p>
                </div>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column prop="linkUrl" label="地址">
            <template #default="scope">
              <p style="display: flex; align-items: center">
                <span style="width: 70px; display: inline-block">链接地址：</span>
                <span v-if="!scope.row.isEdit">{{ scope.row.linkUrl }}</span>
                <el-input v-else v-model="scope.row.linkUrl" style="flex: 1"></el-input>
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="action" label="操作" width="180">
            <template #default="scope">
              <div class="action-item-wrap">
                <!-- 编辑 -->
                <div v-if="!scope.row.isEdit" class="edit" @click="clickEdit(scope.row)">
                  <img src="@/assets/images/mall/edit.png" alt="" />
                </div>
                <div v-else class="edit" @click="editSubmit(scope.row)">
                  <img src="@/assets/images/mall/editOk.png" alt="" />
                </div>

                <div class="del ml24" @click="clickDel(scope.row)"><img src="@/assets/images/mall/del.png" alt="" /></div>
                <div class="my-handle drag ml40"><img src="@/assets/images/mall/drag.png" alt="" /></div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    <AddBanner :optionInfo="optionInfo" @close="closeAdd" @submit="addSubmit"></AddBanner>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from "vue";
import SelectList from "@/components/SelectList";
import Sortable from "sortablejs";
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { ElMessage } from "element-plus";
import { RefreshRight, Check } from "@element-plus/icons-vue";
import AddBanner from "./components/AddBanner.vue";
import {
  getCategoryList,
  getAdvertList,
  addAdvert,
  imgsUpload,
  delAdvert,
  updateSort,
  editAdvert,
  updateToggle
} from "@/api/mall/advert";
import { getFolder } from "@/utils/index";

const selectRef = ref();
const form = ref({ time: 1 });
const pageList = ref([]);
const tableData = ref([]);
const optionInfo = ref({
  isShow: false
});
const currLenObj = ref({});
const defaultPageId = ref(null);

onMounted(async () => {
  // 阻止默认行为
  document.body.ondrop = function (event) {
    event.preventDefault();
    event.stopPropagation();
  };
  rowDrop(); //拖拽行
  refresh();
});

const refresh = async () => {
  await getPageList();
  getList();

  currLenObj.value = {
    num: selectRef.value.currentObj.records,
    total: selectRef.value.currentObj.restrict
  };
  console.log("当前节点===", selectRef.value.currentObj);
};

// const refresh2 = async () => {
//   await getPageList();
//   pageList.value[2].records = 5;
//   getList();

//   currLenObj.value = {
//     num: selectRef.value.currentObj.records,
//     total: selectRef.value.currentObj.restrict
//   };
//   console.log("当前节点===", selectRef.value.currentObj);
// };

//获取左侧page列表数据
const getPageList = async () => {
  await getCategoryList().then(res => {
    if (res.code === 200) {
      for (let item of res.data) {
        item.id = item.categoryId;
      }
      pageList.value = res.data || [];
    }
  });
  const currentObj = selectRef.value.currentObj;
  form.value.time = currentObj.toggle;
};

//根据左侧page id查询广告list数据
const getList = async id => {
  await getAdvertList({ advertisingCategoryId: id ? id : selectRef.value.currentObj.categoryId }).then(res => {
    if (res.code === 200) {
      tableData.value = res.data;
      console.log("aaaaaaaa", selectRef.value.currentObj);
      form.value.time = selectRef.value.currentObj.toggle;
    }
  });
};

const addBanner = () => {
  optionInfo.value.isShow = true;
};

const changeSwiperTime = val => {
  updateToggle({ categoryId: selectRef.value.currentObj.categoryId, toggle: val }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "轮播时间修改成功",
        type: "success"
      });
      // getList();
      refresh();
    }
  });
};

// 点击编辑行
const clickEdit = item => {
  item.isEdit = true;
};
//确认编辑
const editSubmit = item => {
  item.isEdit = false;
  item.img = item.img.split("?")[0];
  // delete item.advertisingId;
  delete item.isEdit;
  // console.log(111, item);
  editAdvert(item).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "编辑成功",
        type: "success"
      });
      // getList();
      refresh();
    }
  });
};
//点击删除
const clickDel = item => {
  // console.log("这是要删除的广告===", item);
  delAdvert({ id: item.advertisingId }).then(res => {
    if (res.code === 200) {
      // getList();
      refresh();
    }
  });
};

// 关闭添加弹窗
const closeAdd = val => {
  optionInfo.value.isShow = false;
};
//确认添加
const addSubmit = list => {
  optionInfo.value.isShow = false;
  const LISt = JSON.parse(JSON.stringify(list));
  // console.log("待上传的图片list", LISt);
  const currentObj = selectRef.value.currentObj;

  let params = [];
  for (let item of LISt) {
    params.push({
      position: currentObj.position,
      categoryId: currentObj.categoryId,
      fileId: item.uid,
      img: item.img.split("?")[0],
      toggle: form.value.time,
      sort: 1,
      linkUrl: item.linkUrl
    });
  }
  addAdvert(params).then(async res => {
    if (res.code === 200) {
      console.log("添加成功");
      refresh();
      uploadIMG(LISt);
    }
  });
};

//将图片上传到业务端服务
const uploadIMG = LISt => {
  const uploadArr = [];
  for (let item of LISt) {
    const nameArr = item.name.split(".");
    uploadArr.push({
      fileId: item.uid,
      objectName: "/dbo-mall" + item.folder, //目录＋文件名称
      url: item.img,
      access: "public-read",
      fileName: item.name, //文件名称
      bucketName: "51-jzt-dev",
      size: item.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    });
  }
  console.log("图片列表===", uploadArr);
  imgsUpload(uploadArr).then(res => {
    console.log(909090, res);
  });
};

const changePage = async val => {
  // console.log("这是点击列表组件返回的id===", val);
  defaultPageId.value = selectRef.value.currentObj.categoryId;
  currLenObj.value = {
    num: selectRef.value.currentObj.records,
    total: selectRef.value.currentObj.restrict
  };
  console.log("当前节点===", selectRef.value.currentObj);
  form.value.time = selectRef.value.currentObj.toggle;
  await getList(val);
};

//拖拽行
const rowDrop = () => {
  const tbody = document.querySelector(".el-table__body-wrapper tbody");
  Sortable.create(tbody, {
    animation: 150,
    ghostClass: "blue-background-class",
    handle: ".my-handle",
    onEnd({ newIndex, oldIndex }) {
      if (newIndex == oldIndex) return;
      tableData.value?.splice(newIndex, 0, tableData.value?.splice(oldIndex, 1)[0]);
      const newArray = tableData.value?.slice(0);
      tableData.value = [];
      nextTick(function () {
        tableData.value = newArray;
        console.log("拖拽后的数据===", tableData.value);
        setSort(tableData.value);
      });
    }
  });
};
//拖拽之后，请求接口更改排序
const setSort = list => {
  const ids = list.map(item => item.advertisingId);
  updateSort(ids).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "排序更改成功",
        type: "success"
      });
      getList();
    }
  });
};
//====================================图片上传========================================================================================

const handleAvatarChangeIcon = (item, file, fileList) => {
  //选中文件触发的change事件
  // console.log(file);
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  // const isLt2M = file.raw.size / 1024 / 1024 < 0.5  //限制上传文件的大小
  if (!isPNG && !isJPG) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
    return false;
  } else {
    item["img"] = URL.createObjectURL(file.raw); //赋值图片的url，用于图片回显功能
    // console.log("这里调用图片上传接口");
    customUpload(item, { file }); //调用上传文件api接口
  }
};

/**
 * 上传
 */
const customUpload = async (item, option) => {
  // 合并已上传和当前上传文件
  const folder = getFolder();
  // const objName = folder + option.file.name;
  const objName = folder + option.file.name.split(".")[0] + new Date().getTime() + "." + option.file.name.split(".")[1];

  ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("图片上传成功，地址为===", res.fileUrl);
      item["img"] = res.fileUrl;
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
  padding: 0;
}
h1 {
  margin: 0;
  padding: 0;
}
:deep(.el-table .el-table__cell) {
  padding: 20px 0;
}
.advert {
  .el-container {
    box-shadow: 4px 5px 16px 0px rgba(4, 19, 74, 0.04);
    border-radius: 10px 10px 0px 0px;
    // border: 1px solid #c2d4e8;
  }
  .el-aside {
    background-color: white;
    border-right: 1px solid #c2d4e8;
    margin-bottom: 0;
    border-radius: 10px 0px 0px 0px;
  }
  .el-main {
    padding-bottom: 0;
    :deep(.el-upload.el-upload--picture-card) {
      height: 110px;
      margin-left: 3px;
    }
    .td-img {
      width: 180px;
      height: 110px;
      border-radius: 10px;
      vertical-align: bottom;
    }
    .upload-wrap {
      position: relative;
      & > p {
        color: white;
        position: absolute;
        background-color: rgba(0, 0, 0, 0.5);
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .swiper-time {
      display: flex;
      justify-content: space-between;
      background-color: #f2f6fc;
      padding: 10px 20px;
      height: 50px;
      .el-form-item {
        margin-bottom: 0;
      }
    }
    .action-item-wrap {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      & > div {
        line-height: 16px;
        cursor: pointer;
      }
      .drag {
        cursor: pointer;
      }
      img {
        width: 16px;
        height: 16px;
        vertical-align: bottom;
      }
    }
  }
}
</style>
